package com.rjjh.springmvc.easymvc;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class DispatcherServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException {
        WebUtil.initWebApp();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取当前请求相关数据
        String requestURL = request.getRequestURI();
        if (requestURL.equals("/favicon.ico")) {
            return;
        }

        if (requestURL != null && requestURL.contains(".")) {
            requestURL = requestURL.substring(0, requestURL.lastIndexOf("."));
        }
//======================================================================
        ControllerBean controllerBean = WebUtil.getControllerBeanByUrl(requestURL);
        if (controllerBean == null) {
            return;
        }
        Class<?> controllerClass = controllerBean.getControllerClass();
        Method controllerMethod = controllerBean.getControllerMethod();
        Object ret = null;
        try {
            Object controllerObject = controllerClass.newInstance();
            ret = controllerMethod.invoke(controllerObject);
            if (ret != null && ret.getClass() == ModelAndView.class) {
                WebUtil.handleResult(request, response, (ModelAndView) ret);
            }
        } catch (Exception e) {

        }
    }
}
